<template>
  <div>
    <el-dialog v-model="dialogVisible" width="80%" align-center :close-on-click-modal="false" :show-close="false"
      :before-close="handleClose" destroy-on-close draggable>
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>会议{{ ruleForm.id ? '编辑' : '新增' }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close">
            <CircleCloseFilled color="#fff" />
          </el-icon>
        </div>
      </template>
      <el-form :model="ruleForm" :rules="rules" label-width="130px" ref="ruleFormRef">
        <!-- 基本信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>基本信息</BaseHead>
          <div class="p-[10px]">

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="会议名称" prop="name">
                  <el-input placeholder="请输入会议名称" v-model="ruleForm.name" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议主题" prop="honorName">
                  <el-input placeholder="请输入会议主题" v-model="ruleForm.meetingTheme" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议类型" prop="meetingTypeId">
                  <el-radio-group v-model="ruleForm.meetingTypeId">
                    <el-radio v-for="item in hylxList" :key="item.code" :value="item.code" :label="item.name"
                      size="large"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="主办单位" prop="operateUnit">
                  <el-input placeholder="请输入主办单位" v-model="ruleForm.operateUnit" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议位置">
                  <el-radio-group v-model="ruleForm.meetingScope">
                    <el-radio value="1" label="国内" size="large"></el-radio>
                    <el-radio value="2" label="国外" size="large"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="协办单位">
                  <el-input placeholder="请输入协办单位" v-model="ruleForm.assistanceUnit" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议地点" prop="meetingPlace">
                  <el-input placeholder="请输入会议地点" v-model="ruleForm.meetingPlace" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="承办部门" prop="unitId">
                  <el-select v-model="ruleForm.unitId" placeholder="请选择承办部门" clearable>
                    <el-option v-for="item in zcgsdwList" :key="item.codeColumn" :label="item.valueColumn"
                      :value="item.codeColumn" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开始日期" prop="beginDate">
                  <el-date-picker v-model="ruleForm.beginDate" type="date" :disabled-date="disableAfterEndDate"
                    format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束日期" prop="endDate">
                  <el-date-picker v-model="ruleForm.endDate" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                    :disabled-date="disableBeforeStartDate" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="简介">
                  <el-input v-model="ruleForm.intro" type="textarea" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="会议相关文档">
                  <FileUpload :uploadUrl="uploadUrl" :limit="1" tip="最多可上传1个附件,每个附件大小不超过20M" v-model="fileList"
                    @change="fileChange">
                  </FileUpload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <!-- 详细信息 -->
        <div class="bg-white mt-[10px]">
          <BaseHead>详细信息</BaseHead>
          <div class="p-[10px]">

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="代表人数">
                  <el-input-number v-model="ruleForm.personNumber" @keydown="inputLimit" :step="1" step-strictly
                    clearable :controls="false" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="论文数量">
                  <el-input-number v-model="ruleForm.paperNumber" @keydown="inputLimit" :step="1" step-strictly
                    clearable :controls="false" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="国外代表数量">
                  <el-input-number v-model="ruleForm.foreignDeputyNumber" @keydown="inputLimit" :step="1" step-strictly
                    clearable :controls="false" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议联系人">
                  <el-input placeholder="请输入会议联系人" v-model="ruleForm.meetingContacts" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议电话" prop="meetingTel">
                  <el-input placeholder="请输入会议电话" v-model="ruleForm.meetingTel" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议邮箱" prop="meetingEmail">
                  <el-input placeholder="请输入会议邮箱" v-model="ruleForm.meetingEmail" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否形成综合报告或建议" label-width="200px">
                  <el-radio-group v-model="ruleForm.isFormReport">
                    <el-radio value="1" size="large">是</el-radio>
                    <el-radio value="0" size="large">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会议经费">
                  <el-input placeholder="请输入会议经费" @input="validateNumber" type="number" v-model="ruleForm.feeTotal"
                    clearable>
                    <template #append>万元</template></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经费来源">
                  <el-input placeholder="请输入经费来源" v-model="ruleForm.feeSource" clearable>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="submitForm(ruleFormRef, '-1')" v-if="ruleForm.checkstatus != '2'"
              :loading="btnLoading">暂存</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)" v-if="checkEditButtonT()"
              :loading="btnLoading">{{
      Cookies.get("role-key") ==
        'biz_kyms' ? '提交' : ruleForm.checkstatus == '2' ? '保存' :
        '保存并通过' }}</el-button>
            <el-button type="primary" @click="initData()">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import FileUpload from "@/views/achievement/components/FileUpload.vue"
import { getmeetingAdd, getmeetingUpdate } from "@/api/achievement/xsjl"
import { ElMessage, ElMessageBox } from "element-plus";
import Cookies from 'js-cookie'
const dialogVisible = defineModel();
const props = defineProps({
  hylxList: Array,
  zcgsdwList: Array,
})
const checkPhone = (rule, value, callback) => {
  const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
  const landlineRegex = /^\d{3}-\d{8}$|^\d{3} \d{8}$|^\d{4}-\d{7}$|^\d{4} \d{7}$/;
  const mobileRegex = /^1[3-9]\d{9}$/;
  if (!value) {
    return callback()
  }
  setTimeout(() => {
    if (landlineRegex.test(value) || mobileRegex.test(value)) {
      callback()
    } else {
      callback(new Error('电话号码格式不正确'))
    }
  }, 100)
}
const checkEmail = (rule, value, callback) => {
  const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
  if (!value) {
    return callback()
  }
  setTimeout(() => {
    if (mailReg.test(value)) {
      callback()
    } else {
      callback(new Error('请输入正确的邮箱格式'))
    }
  }, 100)
}
const ruleForm = reactive({
  name: '',
  meetingTheme: '',
  meetingTypeId: '',
  operateUnit: '',
  assistanceUnit: '',
  meetingPlace: '',
  unitId: '',
  beginDate: '',
  endDate: '',
  intro: '',
  personNumber: null,
  paperNumber: null,
  foreignDeputyNumber: null,
  meetingContacts: '',
  meetingTel: '',
  meetingEmail: '',
  isFormReport: '1',
  feeTotal: '',
  feeSource: '',
  meetingScope: '',
  fileIds: '',
})
const rules = reactive({
  name: [
    { required: true, message: '请输入会议名称', trigger: 'blur' },
  ],
  meetingTheme: [
    { required: true, message: '请输入会议主题', trigger: 'blur' },
  ],
  operateUnit: [
    { required: true, message: '请输入主办单位', trigger: 'blur' },
  ],
  meetingPlace: [
    { required: true, message: '请输入会议地点', trigger: 'blur' },
  ],
  meetingTypeId: [
    {
      required: true,
      message: '请选择会议类型',
      trigger: 'change',
    },
  ],
  unitId: [
    {
      required: true,
      message: '请选择承办部门',
      trigger: 'change',
    },
  ],
  beginDate: [
    {
      required: true,
      message: '请选择开始日期',
      trigger: 'change',
    },
  ],
  endDate: [
    {
      required: true,
      message: '请选择结束日期',
      trigger: 'change',
    },
  ],
  meetingTel: [
    { validator: checkPhone, trigger: 'blur' }
  ],
  meetingEmail: [
    { validator: checkEmail, trigger: 'blur' }
  ],
})

const btnLoading = ref(false)
const ruleFormRef = ref()
const submitForm = async (formEl, i) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      btnLoading.value = true;
      let params = {
        ...ruleForm,
      }
      params.submitType = i ? i : Cookies.get("role-key") == 'biz_kyms' ? '1' : '2'
      // if (i == '-1') {
      //   if (!ruleForm.id || Cookies.get("role-key") == 'biz_kyms') {
      //   } else {
      //     params.submitType = params.checkstatus
      //   }
      // }
      console.log(params, 'params')
      if (params.id) {
        getmeetingUpdate(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            initData()
            emit('callBack', "")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      } else {
        getmeetingAdd(params).then((res) => {
          if (res.code == 200) {
            ElMessage({
              message: res.msg,
              type: 'success',
            })
            initData()
            emit('callBack', "")
          } else {
            ElMessage({
              message: res.msg,
              type: 'error',
            })
          }
          btnLoading.value = false;
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const emit = defineEmits(['callBack']);
const handleClose = (done) => {
  Object.assign(ruleForm, {
    name: '',
    meetingTheme: '',
    meetingTypeId: '',
    operateUnit: '',
    assistanceUnit: '',
    meetingPlace: '',
    unitId: '',
    beginDate: '',
    endDate: '',
    intro: '',
    personNumber: null,
    paperNumber: null,
    foreignDeputyNumber: null,
    meetingContacts: '',
    meetingTel: '',
    meetingEmail: '',
    isFormReport: '1',
    feeTotal: '',
    feeSource: '',
    meetingScope: '',
    fileIds: '',
  })
  fileList.value = []
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  emit('callBack', "")
  done()
}
const initData = () => {
  Object.assign(ruleForm, {
    name: '',
    meetingTheme: '',
    meetingTypeId: '',
    operateUnit: '',
    assistanceUnit: '',
    meetingPlace: '',
    unitId: '',
    beginDate: '',
    endDate: '',
    intro: '',
    personNumber: null,
    paperNumber: null,
    foreignDeputyNumber: null,
    meetingContacts: '',
    meetingTel: '',
    meetingEmail: '',
    isFormReport: '1',
    feeTotal: '',
    feeSource: '',
    meetingScope: '',
    fileIds: '',
  })
  fileList.value = []
  delete ruleForm.id;
  delete ruleForm.checkstatus;
  dialogVisible.value = false
}
const getRuleForm = (i) => {
  for (const key in i) {
    ruleForm[key] = i[key];
  }
  fileList.value = i.fileList.map((item) => {
    return {
      name: item.fileName,
      id: item.id,
    };
  });
  console.log(ruleForm, 'ruleForm')
}
const uploadUrl = `/commonFile/uploadFile?modelName=meetingApply`;
const fileList = ref([]);
//上传的文件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  ruleForm.fileIds = ids.join(",");
};

const checkEditButtonT = () => {
  if (Cookies.get("role-key") == 'biz_kyms') {
    return true
  } else if (Cookies.get("role-key") == 'biz_kycgly') {
    if (ruleForm.checkstatus == '1') {
      return ruleForm.isAuditor ? true : false
    } else {
      return true
    }
  } else {
    return false
  }
}


defineExpose({
  getRuleForm
})

const disableBeforeStartDate = (time) => {
  if (!ruleForm.beginDate) return false; // 如果没有开始日期，则不限制结束日期
  return time.getTime() <= new Date(ruleForm.beginDate).getTime(); // 禁用所有在开始日期之前的日期
}

const disableAfterEndDate = (time) => {
  if (!ruleForm.endDate) return false; // 如果没有开始日期，则不限制结束日期
  return time.getTime() >= new Date(ruleForm.endDate).getTime(); // 禁用所有在开始日期之前的日期
}

const validateNumber = (value) => {
  const minValue = 0; // 定义最小值
  if (value < minValue) {
    ruleForm.feeTotal = minValue; // 或者设置为空字符串或上一个有效值
  }
  // 使用正则表达式限制小数点后最多4位
  ruleForm.feeTotal = value.toString().replace(/[^0-9.]/g, '').replace(/(\.\d{6})\d*/g, '$1');
};



const inputLimit = (e) => {
  const key = e.key;
  const notAllowList = ["e", "E", "+", "-", "."];
  if (notAllowList.includes(key)) {
    e.returnValue = false;
    return false;
  }
  return true;
};

</script>

<style scoped lang="scss">
@import url("@/views/achievement/index.scss");
</style>
